﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FZKJ.COMMON;
using FZKJ.ZHXJ.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace FZKJ.ZHXJ.Controllers
{
    public class UserController : Controller
    {

        public ActionResult AdminManage()
        {
            return View();
        }

        /// <summary>
        /// 获取所有Admin
        /// </summary>
        /// <returns></returns>
        public string GetAllAdmins()
        {
            ResultInfo<List<object>> data = new ResultInfo<List<object>>();
            var dt = new FZKJ.BLL.base_userinfo().GetList("");
            if (dt != null && dt.Rows.Count > 0)
            {
                data.IsSucceed = true;
                data.Message = "获取数据成功！";
                data.TotalCount = dt.Rows.Count;
            }
            else
            {
                data.IsSucceed = false;
                data.Message = "暂无可操作数据！";
                data.TotalCount = 0;
            }
            data.Entity = JsonHelper.DataTableToList(dt);
            return JsonConvert.SerializeObject(data);
        }
        /// <summary>
        /// 保存Admin
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public string AdminManageSave(string json)
        {
            ResultInfo result = new ResultInfo(false);
            JObject jo = JObject.Parse(json);
            LoginInfo userInfo = SessionHelper.ReadSession<LoginInfo>(SessionKeys.LoginInfoKey);
            var bll = new FZKJ.BLL.base_userinfo();

            bool avatar = false;
            string folderName = Server.MapPath("~/Upload/Avatar");
            if (Directory.Exists(folderName) == false) Directory.CreateDirectory(folderName);
            string fileName = Guid.NewGuid().ToString("N");
            string filePath = folderName + "/" + fileName + ".jpg";
            if (jo["avatar"].ToString() == "-1" && jo["base64"].ToString() != "-1" && StringToFile(jo["base64"].ToString(), filePath))
            { avatar = true; }

            //新增
            if (jo["id"].ToString() == "-1")
            {
                var model = new FZKJ.Model.base_userinfo
                {
                    usercode = bll.GetMaxNo(),
                    username = jo["username"].ToString(),
                    phone = jo["phone"].ToString(),
                    pname = jo["pname"].ToString(),
                    rolecode = jo["rolecode"].ToString(),
                    wechat = jo["wechat"].ToString(),
                    password = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile("888888", "MD5"),
                    avatar = avatar ? fileName : jo["avatar"].ToString() == "-1" ? "" : jo["avatar"].ToString(),
                    isenable = 1,
                    createtime = DateTime.Now,
                    createman = userInfo.UserName
                };
                if (bll.Add(model) > 0)
                {
                    result.IsSucceed = true;
                    result.Message = "保存成功,初始密码为888888！";
                    PublicClass.AddLog("操作", "新增内部人员" + model.username + "," + model.pname + "！");
                }
                else
                {
                    result.IsSucceed = false;
                    result.Message = "保存失败！";
                }
            }
            //修改
            else
            {
                int id = int.Parse(jo["id"].ToString());
                var umodel = bll.GetModel(id);
                string oldstr = JsonHelper.GetObjectToJSON(umodel);
                umodel.phone = jo["phone"].ToString();
                umodel.pname = jo["pname"].ToString();
                umodel.wechat = jo["wechat"].ToString();
                umodel.rolecode = jo["rolecode"].ToString();
                umodel.avatar = avatar ? fileName : jo["avatar"].ToString() == "-1" ? "" : jo["avatar"].ToString();
                umodel.updateman = userInfo.UserName;
                umodel.updatetime = DateTime.Now;
                string newstr = JsonHelper.GetObjectToJSON(umodel);

                if (bll.Update(umodel) > 0)
                {
                    result.IsSucceed = true;
                    result.Message = "保存成功！";
                    PublicClass.AddLog("操作", "修改内部人员" + umodel.username + "！", "", "", "base_userinfo", umodel.id.ToString(), oldstr, newstr);
                }
                else
                {
                    result.IsSucceed = false;
                    result.Message = "保存失败！";
                }
            }
            return JsonConvert.SerializeObject(result);
        }

        /// <summary> 
        /// 把经过base64编码的字符串保存为文件 
        /// </summary> 
        /// <param name="base64String">经base64加码后的字符串 </param> 
        /// <param name="fileName">保存文件的路径和文件名 </param> 
        /// <returns>保存文件是否成功 </returns> 
        public static bool StringToFile(string base64String, string fileName)
        {
            bool bl = false;
            System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Create);
            System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs);
            try
            {
                if (!string.IsNullOrEmpty(base64String) && System.IO.File.Exists(fileName))
                {
                    //base64String = base64String.Replace("data:image/png;base64,", "");
                    base64String = base64String.Split(',')[1];
                    bw.Write(Convert.FromBase64String(base64String));
                    bw.Dispose();
                    fs.Dispose();
                    bw.Close();
                    fs.Close();
                }
                bl = true;
            }
            catch (Exception ex)
            {
                PublicClass.AddLog("保存图片", "StringToFile", fileName + "---" + ex.ToString());
            }
            finally
            {
                bw.Dispose();
                fs.Dispose();
                bw.Close();
                fs.Close();
                GC.Collect();
            }
            return bl;
        }

        /// <summary>
        /// Admin启用或禁用
        /// </summary>
        /// <param name="id"></param>
        /// <param name="ised"></param>
        /// <returns></returns>
        public string AdminEnableOrDisabled(int id, string ised)
        {
            ResultInfo<string> result = new ResultInfo<string>();
            var bll = new FZKJ.BLL.base_userinfo();
            var model = bll.GetModel(id);
            model.isenable = int.Parse(ised);
            if (bll.Update(model) > 0)
            {
                result.IsSucceed = true;
                result.Message = "操作成功！";
                PublicClass.AddLog("操作", (model.isenable == 1 ? "启用内部人员：" : "禁用内部人员：") + model.username + "," + model.pname + "!");
            }
            else
            {
                result.IsSucceed = false;
                result.Message = "操作失败！";
            }
            return JsonConvert.SerializeObject(result);
        }


        public ActionResult UserManage()
        {
            return View();
        }

        /// <summary>
        /// 会员管理
        /// </summary>
        /// <returns></returns>
        public ActionResult MemberManage()
        {
            return View();
        }

        public string GetMembers()
        {
            var data = new ResultInfo<List<object>>();
            var pageSize = int.Parse(Request.Params["pagesize"]);
            var pageNo = int.Parse(Request.Params["pageno"]);
            var order = Request.Params["order"];
            //查询条件组织
            var where = " (isdel is null or isdel=0) AND ";
            if (!string.IsNullOrWhiteSpace(Request.Params["query"]))
            {
                string query = Request.Params["query"];
                where += $" (name like'%{query}%' or mobile like'%{query}%' or emergencycontact like '%{query}%') AND ";
            }
            if (!string.IsNullOrWhiteSpace(Request.Params["level"]))
            {
                where += $" grade ={Request.Params["level"]} AND ";
            }
            if (!string.IsNullOrEmpty(where))
                where = where.Substring(0, where.Length - 4);
            var startIndex = pageSize * (pageNo - 1) + 1;
            var endIndex = pageSize * pageNo;
            var dt = new BLL.buss_members().GetListByPage(where, order, startIndex, endIndex).Tables[0];
            data.IsSucceed = true;
            data.TotalCount = new BLL.buss_members().GetListByPage(where, order, -1, -1).Tables[0].Rows.Count;
            data.Entity = JsonHelper.DataTableToList(dt);
            return JsonConvert.SerializeObject(data);
        }



        [HttpPost]
        public string SaveMember(string json)
        {
            ResultInfo result = new ResultInfo(false);
            try
            {
                LoginInfo li = SessionHelper.ReadSession<LoginInfo>(SessionKeys.LoginInfoKey);
                var model = JsonConvert.DeserializeObject<Model.buss_members>(json);
                if (model.id == "-1")
                {
                    model.id = Guid.NewGuid().ToString().Replace("-", "").ToLower();
                    model.code = GenerateCode.GetCode();
                    new BLL.buss_members().Add(model);
                    result.IsSucceed = true;
                    result.Message = "添加成功";
                }
                else
                {
                    var m = new BLL.buss_members().GetModel(model.code); ;
                    m.name = model.name;
                    m.sex = model.sex;
                    m.cardno = model.cardno;
                    m.mobile = model.mobile;
                    m.bloodType = model.bloodType;
                    m.emergencycontact = model.emergencycontact;
                    m.emergencycontactrelation = model.emergencycontactrelation;
                    m.emergencycontactmobile = model.emergencycontactmobile;
                    m.cardpic = model.cardpic;
                    m.point = model.point;
                    m.presentaddress = model.presentaddress;
                    m.illnesshistory = model.illnesshistory;
                    m.grade = model.grade;
                    m.receiveaddress = model.receiveaddress;
                    new BLL.buss_members().Update(m);
                    result.IsSucceed = true;
                    result.Message = "添加成功";

                }
            }
            catch (Exception exception)
            {
                result.IsSucceed = false;
                result.Message = "添加失败";
            }

            return JsonConvert.SerializeObject(result);
        }

        [HttpPost]
        public string DeleteMembers(string ids)
        {
            ResultInfo result = new ResultInfo(false);
            try
            {
                foreach (var item in ids.Split(','))
                {
                    var model = new BLL.buss_members().GetModel(item);
                    model.isdel = 1;
                    new BLL.buss_members().Update(model);
                }
                result.IsSucceed = true;
                result.Message = "删除成功";
            }
            catch (Exception e)
            {
                result.IsSucceed = false;
                result.Message = "删除失败";
            }
            return JsonConvert.SerializeObject(result);
        }
        public string UploadFile(string path)
        {
            HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
            string path1 = Server.MapPath("~/Resourse/");
            string returnPath = "";
            string fileName = "";
            string newName = Guid.NewGuid().ToString().Replace("-", "");
            if (!Directory.Exists(path1))//不存在这个文件夹就创建这个文件夹 
            {
                Directory.CreateDirectory(path1);
            }
            if (hfc.Count > 0)
            {
                fileName = hfc[0].FileName;
                newName = newName + "." + hfc[0].FileName.Split('.')[1].ToLower();
                hfc[0].SaveAs(path1 + newName);
            }
            else
            {
                return "0";
            }
            return  newName;
        }

        [HttpPost]
        public string SaveMemberPolicy(string json)
        {
            ResultInfo result = new ResultInfo(false);
            try
            {
                LoginInfo li = SessionHelper.ReadSession<LoginInfo>(SessionKeys.LoginInfoKey);
                var model = JsonConvert.DeserializeObject<Model.buss_insurance>(json);
                model.id = Guid.NewGuid().ToString().Replace("-", "").ToLower();
                var list = new BLL.buss_insurance().GetModelList(" memberid='" + model.memberid + "'");
                foreach (var item in list)
                {
                    item.islose = 1;
                    item.losetime = DateTime.Now;
                    new BLL.buss_insurance().Update(item);
                }
                new BLL.buss_insurance().Add(model);
                result.IsSucceed = true;
                result.Message = "添加成功";
            }
            catch (Exception exception)
            {
                result.IsSucceed = false;
                result.Message = "添加失败";
            }
            return JsonConvert.SerializeObject(result);

        }
        [HttpPost]
        public string SaveMemberRes(string json)
        {
            ResultInfo result = new ResultInfo(false);
            try
            {
                LoginInfo li = SessionHelper.ReadSession<LoginInfo>(SessionKeys.LoginInfoKey);
                var model = JsonConvert.DeserializeObject<Model.buss_rescue>(json);
                model.id = Guid.NewGuid().ToString().Replace("-", "").ToLower();
                var list = new BLL.buss_rescue().GetModelList(" memberid='" + model.memberid + "'");
                foreach (var item in list)
                {
                    item.isdel = 1;
                    item.deltime = DateTime.Now;
                    new BLL.buss_rescue().Update(item);
                }
                new BLL.buss_rescue().Add(model);
                result.IsSucceed = true;
                result.Message = "添加成功";
            }
            catch (Exception exception)
            {
                result.IsSucceed = false;
                result.Message = "添加失败";
            }

            return JsonConvert.SerializeObject(result);

        }

        /// <summary>
        /// 会员等级管理
        /// </summary>
        /// <returns></returns>
        public ActionResult LevelManage()
        {
            return View();
        }
        public string GetLevle()
        {
            var data = new ResultInfo<List<object>>();
            var pageSize = int.Parse(Request.Params["pagesize"]);
            var pageNo = int.Parse(Request.Params["pageno"]);
            var order = Request.Params["order"];
            //查询条件组织
            var where = string.Empty;

            if (!string.IsNullOrEmpty(where))
                where = where.Substring(0, where.Length - 4);
            var startIndex = pageSize * (pageNo - 1) + 1;
            var endIndex = pageSize * pageNo;
            var dt = new BLL.buss_membergrade().GetListByPage(" (isdel is null or isdel=0)", order, startIndex, endIndex).Tables[0];
            data.IsSucceed = true;
            data.TotalCount = new BLL.buss_membergrade().GetRecordCount("(isdel is null or isdel=0)");
            data.Entity = JsonHelper.DataTableToList(dt);
            return JsonConvert.SerializeObject(data);
        }
        [HttpPost]
        public string SaveLevle(string json)
        {
            ResultInfo result = new ResultInfo(false);
            try
            {
                LoginInfo li = SessionHelper.ReadSession<LoginInfo>(SessionKeys.LoginInfoKey);
                var model = JsonConvert.DeserializeObject<Model.buss_membergrade>(json);
                if (model.id == -1)
                {
                    model.creater = new BLL.base_userinfo().GetModelList(" username='" + li.UserName + "'")[0].id;
                    model.createtime = DateTime.Now;
                    new BLL.buss_membergrade().Add(model);
                    result.IsSucceed = true;
                    result.Message = "添加成功";
                }
                else
                {
                    var m = new BLL.buss_membergrade().GetModel(model.id);
                    m.name = model.name;
                    m.discount = model.discount;
                    m.updater = new BLL.base_userinfo().GetModelList(" username='" + li.UserName + "'")[0].id;
                    m.updatetime = DateTime.Now;
                    new BLL.buss_membergrade().Update(m);
                    result.IsSucceed = true;
                    result.Message = "添加成功";

                }
            }
            catch (Exception exception)
            {
                result.IsSucceed = false;
                result.Message = "添加失败";
            }

            return JsonConvert.SerializeObject(result);
        }

        [HttpPost]
        public string DeleteLevle(string ids)
        {
            ResultInfo result = new ResultInfo(false);
            try
            {
                foreach (var item in ids.Split(','))
                {
                    var model = new BLL.buss_membergrade().GetModel(Convert.ToInt32(item));
                    model.isdel = 1;
                    model.deltime = DateTime.Now;
                    new BLL.buss_membergrade().Update(model);
                }
                result.IsSucceed = true;
                result.Message = "删除成功";
            }
            catch (Exception e)
            {
                result.IsSucceed = false;
                result.Message = "删除失败";
            }
            return JsonConvert.SerializeObject(result);
        }
    }
}
